#!/bin/bash
set -x
set -e
apiserver_vip_domain=${1}
apiserver_vip_port=${2}
cluster=${3}

echo "cluster: ${cluster}; apiserver_vip_domain: ${apiserver_vip_domain}; apiserver_vip_port: ${apiserver_vip_port}"

ls /etc/kubernetes/${cluster}/controller-manager.conf && exit 0

cd /etc/kubernetes/${cluster}/
cat > openssl-client.conf << EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
EOF

genconfig() {
    name=${1}
    subj=${2}
    mkdir -p pkitmp
    kubectl config set-cluster kubernetes --certificate-authority=pki/ca.crt \
        --embed-certs=true --server=https://${apiserver_vip_domain}:${apiserver_vip_port} \
        --kubeconfig=${name}.conf
    openssl genrsa -out pkitmp/${name}.key 2048
    openssl req -new -key pkitmp/${name}.key -out pkitmp/${name}.csr -subj "${subj}" -config openssl-client.conf
    openssl x509 -req -in pkitmp/${name}.csr -CA pki/ca.crt -CAkey pki/ca.key -CAcreateserial -out pkitmp/${name}.crt \
        -days 3650 -extensions v3_req  -extfile openssl-client.conf
    kubectl config set-credentials kubernetes-${name} --client-certificate=pkitmp/${name}.crt \
        --embed-certs=true --client-key=pkitmp/${name}.key --kubeconfig=${name}.conf
    kubectl config set-context kubernetes-${name}@kubernetes --cluster=kubernetes --user=kubernetes-${name} --kubeconfig=${name}.conf
    kubectl config use-context kubernetes-${name}@kubernetes --kubeconfig=${name}.conf
    rm -rf pkitmp
}

# admin
genconfig admin "/O=system:masters/CN=kubernetes-admin"
# kube-controller-manager
genconfig controller-manager "/CN=system:kube-controller-manager"
# kube-scheduler
genconfig scheduler "/CN=system:kube-scheduler"

rm -f openssl-client.conf
